﻿using UnityEngine;

namespace CGF
{
    public class PrefabComponentBase : ComponentBase, IDestroy
    {
        public GameObject gameObject { get; private set; }
        public Transform transform { get; private set; }
        protected static int idCounter = 0;

        protected async CTask<bool> SpawnPrefab(string prefabPath, Transform parent)
        {
            GameObject prefab = await ResManager.Instance.LoadAsset<GameObject>(prefabPath);
            if (!prefab)
            {
                LogError($"加载预置体失败（是否AB属于延迟加载部分？否则Shift+A,勾选自动更新）[{prefabPath}]");
                return false;
            }
            gameObject = GameObject.Instantiate(prefab, parent, false);
            transform = gameObject.transform;
            gameObject.AddEnableEvent(OnEnable);
            gameObject.AddDisableEvent(OnDisable);
            return true;
        }

        protected static int GenerateId()
        {
            idCounter++;
            return idCounter;
        }

        public virtual void OnEnable() { }
        public virtual void OnDisable() { }

        public virtual void OnDestroy()
        {
            if (gameObject)
            {
                gameObject.RemoveEnableEvent(OnEnable);
                gameObject.RemoveEnableEvent(OnDisable);
                GameObject.Destroy(gameObject);
            }
        }
    }
}
